package cn.bugio.note.rocketmq.user;

import cn.bugio.note.common.domain.messaging.UserAndBonusMsgDTO;
import cn.bugio.note.dao.user.BonusEventLogMapper;
import cn.bugio.note.dao.user.UserMapper;
import cn.bugio.note.domain.entity.user.BonusEventLog;
import cn.bugio.note.domain.entity.user.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/3/1
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "conten-center", topic = "add-bonus")
public class AddBounsListener implements RocketMQListener<UserAndBonusMsgDTO> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BonusEventLogMapper bonusEventLogMapper;

    @Override
    public void onMessage(UserAndBonusMsgDTO userAndBonusMsgDTO) {
        //当收到消息的时候执行业务
        //1.为用户加积分
        log.info("接收消息 --> {}" ,userAndBonusMsgDTO);

        if (userAndBonusMsgDTO.getUserId() == null){
            return;
        }


        Integer userId = userAndBonusMsgDTO.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        Integer bonus = userAndBonusMsgDTO.getBonus();
        user.setBonus(user.getBonus()+ bonus);
        userMapper.updateByPrimaryKeySelective(user);

        //2.记录日志到bouns_event
        BonusEventLog build1 = BonusEventLog.builder().userId(userAndBonusMsgDTO.getUserId()).event("add " + bonus).build();
        bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("CONTRIBUTE")
                        .createTime(new Date())
                        .description("投稿添加积分")
                        .build()
        );

    }
}
